// pages/teacherattendance/teacherattendance.js
const app = getApp()
var util = require("../../utils/util.js");
const MONTHS = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'June.', 'July.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    actions: [{
        name: '同意',
      },
      {
        name: '不同意',
      }
    ],
    contentid: 0,
    teachername: "",
    teacherList: [],
    active: 0,
    activeday: 0,
    currentyear: null,
    currentmonth: null,
    year: null,
    month: null,
    selectdate: util.formatDate(new Date()),
    selectdateday: util.formatDate(new Date()),
    currentdate: util.formatDate(new Date()),
    enddate: util.formatDate(new Date()),
    startdate: util.formatDateMonth(new Date('2000-01-01')),


    allteachercount: 0,
    attandancecount: 0,
    noattandancecount: 0,
    leaveEarlycount: 0,
    attendanceLatecount: 0,
    missingCardcount: 0,
    leaveTeachercount: 0,
    offDutycount: 0,

    attendanceList: [],
    noAttendanceList: [],
    attendanceLateList: [],
    leaveEarlyList: [],
    offDutyList: [],
    missingCardList: [],
    leaveTeacherList: [],

    hidden: true, //隐藏表单控件
    page: 1, //当前请求数据是第几页
    pageSize: 10, //每页数据条数
    hasMoreData: true, //上拉时是否继续请求数据，即是否还有更多数据
    contentlist: null,
  },

  onChange(event) {
    console.log("event================" + event.detail.index)
    this.setData({
      active: event.detail.index
    })


    if (event.detail.index == 0) {
      this.get_attendance_month()
    } else if (event.detail.index == 1) {
      this.get_attendance_day();
    } else {
      this.data.page = 1
      this.get_leave('正在加载数据...')
    }
  },

  dayChange(event) {
    console.log("event================" + event.detail.index)
    this.setData({
      activeday: event.detail.index
    })

  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var year = new Date().getFullYear()
    var month = new Date().getMonth() + 1
    var month1 = parseInt(month)
    if (month1 < 10) {
      month1 = '0' + month1;
    }
    var selectdate = year + "-" + month1
    this.setData({
      year: parseInt(year),
      month: parseInt(month),
      currentyear: parseInt(year),
      currentmonth: parseInt(month),
      selectdate: selectdate,
    })
    console.log("year===" + year)
    console.log("month===" + month)
    this.get_attendance_month()

  },
  buqianClick: function () {
    var that = this
    var arr = this.data.noAttendanceList;
    var teacheridStr = ""
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].status == 1) {
        teacheridStr += "," + arr[i].teacherID
      }
    }
    if (teacheridStr.length > 0) {
      teacheridStr = teacheridStr.substring(1)
      this.setbuqian(teacheridStr, 1);
    } else {
      wx.showToast({
        title: '请选择补签的教师',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    }
    console.log("点击");

  },

  //补签
  setbuqian: function (teacheridstr, status) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "teacheridstr": teacheridstr,
      "status": status, ///1入园   2离园
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "mobileType": app.globalData.mobileType,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "confirm_attendances_teacher"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        if (res.data.status == 0) {
          wx.showToast({
            title: '补签成功',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          if (that.data.active == 0) {
            that.get_attendance_month()
          } else {
            that.get_attendance_day();
          }
        } else {
          wx.showToast({
            title: '补签失败',
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: '补签失败',
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        console.log('submit complete');
      }
    })
  },

  weidaoClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var arr = this.data.noAttendanceList;
    var obj = this.data.noAttendanceList[index]
    if (obj.status == 0 || obj.status == null) {
      obj.status = 1
    } else {
      obj.status = 0
    }
    arr[index] = obj
    this.setData({
      noAttendanceList: arr
    })
    console.log("点击");

  },
  yidaoClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.attendanceList[index].teacherID
    var teachername = this.data.attendanceList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })
  },
  chidaoClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.attendanceLateList[index].teacherID
    var teachername = this.data.attendanceLateList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })

  },
  zaotuiClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.leaveEarlyList[index].teacherID
    var teachername = this.data.leaveEarlyList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })

  },

  qingjiaClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.offDutyList[index].teacherID
    var teachername = this.data.offDutyList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })

  },

  quekaClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.missingCardList[index].teacherID
    var teachername = this.data.missingCardList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })

  },
  xiubanClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var teacherid = this.data.offDutyList[index].teacherID
    var teachername = this.data.offDutyList[index].name
    //打开
    console.log("点击");
    wx.navigateTo({
      url: '../teacherattendancedetail/teacherattendancedetail?teacherid=' + teacherid + "&teachername=" + teachername
    })

  },

  onClose() {
    this.setData({
      show: false
    });
  },
  onCancel() {
    this.setData({
      show: false
    });
  },
  onSelect(event) {
    console.log(event.detail);
    if (event.detail.name == '同意') {
      this.shenhe(1)
    } else {
      this.shenhe(2)
    }
  },

  shenheClick: function (e) {
    var index = e.currentTarget.dataset.index;
    var contentid = this.data.contentlist[index].leaveID
    var teachername = this.data.contentlist[index].Name

    this.setData({
      contentid: contentid,
      teachername: teachername,
      show: true
    })
  },



  //请假处理
  shenhe: function (isagree) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "isagree": isagree,
      "contentid": that.data.contentid,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "send_leavecheck"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          wx.showToast({
            title: "操作成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          that.data.page = 1
          that.get_leave('正在加载数据...')
        } else {
          wx.showToast({
            title: "操作失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "操作失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },




  //月度报表
  get_attendance_month: function () {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "year": that.data.year,
      "month": that.data.month,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileType": app.globalData.mobileType,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "get_attendance_month_new171120"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          var teacherList = res.data.teacherList
          that.setData({
            teacherList: teacherList
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "获取数据失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  //当日详情
  get_attendance_day: function () {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "date": that.data.selectdateday,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileType": app.globalData.mobileType,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "get_attendance_day_new171120"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {

          that.setData({

            allteachercount: res.data.allteachercount,
            attandancecount: res.data.attandancecount,
            noattandancecount: res.data.noAttendanceList.length,
            leaveEarlycount: res.data.leaveEarlyList.length,
            attendanceLatecount: res.data.attendanceLateList.length,
            missingCardcount: res.data.MissingCardList.length,
            leaveTeachercount: res.data.leaveTeacherList.length,
            offDutycount: res.data.offDutyList.length,

            attendanceList: res.data.attendanceList,
            noAttendanceList: res.data.noAttendanceList,
            attendanceLateList: res.data.attendanceLateList,
            leaveEarlyList: res.data.leaveEarlyList,
            offDutyList: res.data.offDutyList,
            missingCardList: res.data.MissingCardList,
            leaveTeacherList: res.data.leaveTeacherList,
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "获取数据失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  //请假
  get_leave: function (message) {
    var that = this;
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: message,
    })
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "pagenum": that.data.page,
      "pagesize": that.data.pageSize,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileType": app.globalData.mobileType,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "get_leave_teacher"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          var contentlistTem = that.data.contentlist;
          if (res.data.data.length > 0) {
            wx.hideNavigationBarLoading() //在当前页面隐藏导航条加载动画
            wx.hideLoading() //隐藏 loading 提示框
            if (that.data.page == 1) {
              contentlistTem = []
            }
            var contentlist = res.data.data;

            contentlist.forEach(function (item, index) {
              console.log(item); //这里的item就是从数组里拿出来的每一个每一组
              try {
                contentlist[index].leaveReason = decodeURIComponent(item.leaveReason)
              } catch (error) {
                // 此处是负责例外处理的语句
                contentlist[index].leaveReason = item.leaveReason
              } finally {
                // 此处是出口语句
              }
            })


            if (contentlist.length < that.data.pageSize) {
              that.setData({
                contentlist: contentlistTem.concat(contentlist),
                hasMoreData: false
              })
            } else {
              that.setData({
                contentlist: contentlistTem.concat(contentlist),
                hasMoreData: true,
                page: that.data.page + 1
              })
            }
          } else {
            wx.hideNavigationBarLoading()
            wx.hideLoading()
          }
        } else {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "获取数据失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  bindDateChange: function (e) {
    console.log(e)
    var selectdate = e.detail.value
    var year = selectdate.substring(0, 4)
    var month = selectdate.substring(5, 7)
    this.setData({
      year: parseInt(year),
      month: parseInt(month),
      selectdate: selectdate
    })
    this.get_attendance_month();
  },


  bindDateQiantuiChange: function (e) {
    console.log(e)
    this.setData({
      selectdateday: e.detail.value
    })
    this.get_attendance_day();
  },
  btnQiantuiPreday: function () {
    var day = this.getDateStr(this.data.selectdateday, -1);
    this.setData({
      selectdateday: day
    })
    this.get_attendance_day();
  },

  btnQiantuiNextday: function () {
    if (this.data.selectdateday < this.data.currentdate) {
      var day = this.getDateStr(this.data.selectdateday, 1);
      this.setData({
        selectdateday: day
      })
      this.get_attendance_day();
    } else {
      wx.showToast({
        title: '还未到达明天',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    }
  },
  getDateStr: function (today, addDayCount) {
    var dd;
    if (today) {
      dd = new Date(today);
    } else {
      dd = new Date();
    }
    dd.setDate(dd.getDate() + addDayCount); //获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期 
    var d = dd.getDate();
    if (m < 10) {
      m = '0' + m;
    }
    if (d < 10) {
      d = '0' + d;
    };
    return y + "-" + m + "-" + d;
  },

  btnPreday: function () {
    var year = this.data.year
    var month = this.data.month

    if (month == 1) {
      month = 12
      year = year - 1
    } else {
      month = month - 1;
    }
    var month1 = month
    if (month1 < 10) {
      month1 = '0' + month1;
    }
    var selectdate = year + "-" + month1
    this.setData({
      year: year,
      month: month,
      selectdate: selectdate
    })
    this.get_attendance_month();
  },

  btnNextday: function () {
    var year = this.data.year
    var month = this.data.month
    if (year == this.data.currentyear && month == this.data.currentmonth) {
      wx.showToast({
        title: '还未到达得下个月',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    } else {
      if (month == 12) {
        month = 1
        year = year + 1
      } else {
        month = month + 1;
      }
      var month1 = month
      if (month1 < 10) {
        month1 = '0' + month1;
      }
      var selectdate = year + "-" + month1
      this.setData({
        year: year,
        month: month,
        selectdate: selectdate
      })

    }
    this.get_attendance_month();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.active == 0) {
      this.get_attendance_month()
    } else if (this.data.active == 1) {
      this.get_attendance_day();
    } else {
      this.data.page = 1
      this.get_leave('正在加载数据...')
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.active == 0) {
      this.get_attendance_month()
    } else if (this.data.active == 1) {
      this.get_attendance_day();
    } else {
      this.data.page = 1
      this.get_leave('正在加载数据...')
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

    if (this.data.active == 0) {
      this.get_attendance_month()
    } else if (this.data.active == 1) {
      this.get_attendance_day();
    } else {
      if (this.data.hasMoreData) {
        this.get_leave('加载更多数据')
      } else {
        wx.showToast({
          title: '没有更多数据',
        })
      }
    }



  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})